package config

import (
	"context"
	"gitee.com/bobo-rs/innovideo-services/framework/dao"
	"gitee.com/bobo-rs/innovideo-services/framework/model"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

// ProcessGroupScan 扫描配置组数据
func (c *sConfig) ProcessGroupScan(ctx context.Context, where, scan interface{}) error {
	if where == nil || g.IsNil(where) {
		return gerror.New(`缺少请求参数`)
	}
	return dao.ConfigGroup.Ctx(ctx).Where(where).Scan(scan)
}

// ProcessGroupGroupNameById 通过配置组ID获取配置组关联名
func (c *sConfig) ProcessGroupGroupNameById(ctx context.Context, id ...uint) (map[uint]string, error) {
	if len(id) == 0 || (len(id) > 0 && id[0] == 0) {
		return nil, gerror.New(`缺少配置组ID`)
	}
	var (
		groupMap = make(map[uint]string)
		list     []model.ConfigGroupCategoryItem
	)
	err := c.ProcessGroupScan(ctx, g.Map{
		dao.ConfigGroup.Columns().Id: id,
	}, &list)
	if err != nil {
		return nil, err
	}

	// 迭代处理
	for _, item := range list {
		groupMap[item.Id] = item.GroupName
	}
	return groupMap, nil
}

// ProcessGroupTotal 获取配置组总数
func (c *sConfig) ProcessGroupTotal(ctx context.Context, where interface{}) (int, error) {
	if where == nil || g.IsNil(where) {
		return 0, gerror.New(`缺少请求参数`)
	}
	return dao.ConfigGroup.Ctx(ctx).Where(where).Count()
}

// ProcessGroupDetailById 获取配置组详情
func (c *sConfig) ProcessGroupDetailById(ctx context.Context, id uint, detail interface{}) error {
	if id == 0 {
		return gerror.New(`缺少配置组ID`)
	}
	return c.ProcessGroupScan(
		ctx, g.Map{dao.ConfigGroup.Columns().Id: id}, detail,
	)
}

// ProcessGroupDetailByGroupName 根据配置组名获取配置详情
func (c *sConfig) ProcessGroupDetailByGroupName(ctx context.Context, groupName string, detail interface{}) error {
	if len(groupName) == 0 {
		return gerror.New(`缺少配置组名`)
	}
	return c.ProcessGroupScan(ctx, g.Map{
		dao.ConfigGroup.Columns().GroupName: groupName,
	}, detail)
}

// ProcessGroupExists 验证配置组是否存在
func (c *sConfig) ProcessGroupExists(ctx context.Context, where interface{}) (bool, error) {
	total, err := c.ProcessGroupTotal(ctx, where)
	if err != nil {
		return false, err
	}
	return total > 0, nil
}

// ProcessGroupExistsById 根据配置组ID验证配置组是否存在
func (c *sConfig) ProcessGroupExistsById(ctx context.Context, id uint) bool {
	b, _ := c.ProcessGroupExists(ctx, g.Map{
		dao.ConfigGroup.Columns().Id: id,
	})
	return b
}

// ProcessGroupExistsByGroupName 根据配置组组名验证配置组是否存在
func (c *sConfig) ProcessGroupExistsByGroupName(ctx context.Context, name string) bool {
	b, _ := c.ProcessGroupExists(ctx, g.Map{
		dao.ConfigGroup.Columns().GroupName: name,
	})
	return b
}
